﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.IO;
using System.Data;
using System.Drawing;
using System.Windows.Media.Imaging;
using CapaPresentacion.Vistas;

namespace CapaPresentacion.Utilidades
{
   public static class ImageUtil
    {


        public static byte[] Image2Bytes(System.Drawing.Image img)
        {
            string sTemp = Path.GetTempFileName();
            FileStream fs = new FileStream(sTemp, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            img.Save(fs, System.Drawing.Imaging.ImageFormat.Png);
            fs.Position = 0;
            //
            int imgLength = Convert.ToInt32(fs.Length);
            byte[] bytes = new byte[imgLength];
            fs.Read(bytes, 0, imgLength);
            fs.Close();
            return bytes;
        }

        public static System.Drawing.Image Bytes2Image(byte[] bytes)
        {
            if (bytes == null) return null;
            //
            MemoryStream ms = new MemoryStream(bytes);
            System.Drawing.Bitmap bm = null;
            try
            {
                bm = new System.Drawing.Bitmap(ms);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            return bm;
        }


        public static BitmapImage Bytes2BitmapImage(byte[] rawImageBytes)
        {
            BitmapImage b = new BitmapImage();

            try
            {

                using (MemoryStream stream = new MemoryStream(rawImageBytes))
                {
                    b.BeginInit();

                    b.CacheOption = BitmapCacheOption.OnLoad;

                    b.StreamSource = stream;

                    b.EndInit();
                                       
                }


                return b;
            }
            catch (System.Exception)
            {
                VentanaAviso nueva = new VentanaAviso(true, "Se ha producido un error", "Ha pcurrido un error al intentar cargar la imagen del alumno");
                nueva.ShowDialog();
            }


            return b;
        }




    }
}
